package com.zmy.xcx.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zmy.xcx.dao.entity.WxUser;
import com.zmy.xcx.dao.mapper.WxUSerMapper;
import com.zmy.xcx.pojo.dto.UserLoginDTO;
import com.zmy.xcx.properties.WeChatProperties;
import com.zmy.xcx.service.UserService;
import com.zmy.xcx.utils.HttpClientUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class UserServiceImpl extends ServiceImpl<WxUSerMapper,WxUser> implements UserService {
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    private final WeChatProperties weChatProperties;

    @Override
    public WxUser wxLogin(UserLoginDTO userLoginDTO) {
        //1.调用微信服务接口
        String openid = getOpenid(userLoginDTO.getCode());
        log.info("openid:{}",openid);
        //2.判断openid是否为空，空就登录失败
        if (openid  == null) {
            throw new RuntimeException("登录失败,openid为空");
        }
        //3.判断用户是否注册，没注册就自动注册
        WxUser wxUser = lambdaQuery().eq(WxUser::getOpenid, openid).one();
        if (wxUser == null) {
            //注册
            wxUser = new WxUser().builder()
                    .openid(openid)
                    .createAt(LocalDateTime.now())
                    .updateAt(LocalDateTime.now())
                    .build();
            //插入数据库
             this.save(wxUser);

        }
        //4.返回用户信息
        return wxUser;
    }

    /**
     * 调用微信服务接口,获取微信用户的openid
     * @param code
     * @return
     */
    private String getOpenid(String code){
        //调用微信服务接口
        Map<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        log.info("请求微信登录接口参数:{}",map);
        String json = HttpClientUtil.doGet(WX_LOGIN, map);

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");

        return openid;
    }
}
